import axios, { type AxiosRequestHeaders } from "axios";
import storage from "@/utils/storage";
import router from "@/router";
const instance = axios.create({
  baseURL: import.meta.env.VITE_URL,
  timeout: 10000,
});
// var gconfig = {} as any;
instance.interceptors.request.use(
  function (config: any) {
    // gconfig = config;
    if (!config.headers) {
      config.headers = {} as AxiosRequestHeaders;
    }
    if (storage.get("token")) {
      config.headers.authorization = `Bearer ${storage.get("token")}`;
    }

    return config;
  },
  function (error: any) {
    return Promise.reject(error);
  }
);
instance.interceptors.response.use(
  async function (response: any) {
    if (response.data.code == 200) {
      return response.data;
    }
    if (response.data.code == 100) {
      return response.data;
    }
    if (response.data.code == 401) {
      storage.clear();
      router.replace("/login");
      return Promise.reject(response.data);
    } else {
      return Promise.reject(response.data);
    }
  },
  function (error: any) {
    return Promise.reject(error);
  }
);

export { instance };
